#coding:utf-8
from datetime import datetime
import os
from time import sleep, time
from libbase import singleton
from libbase import Terminal
from libbase import TickCenter
from libbase import Utils
from libbase import EventCenter
import events

#connect phase, 0 => not connect, 1 => connecting, 2 => connected
class BlueToothDevice:
    def __init__(self, mac) -> None:
        self.mac = mac
        self.exists = True
        self.connected = False
        self.trusted = False
        self.paired = False
        self.isconnecting = False
        self.connectTime = 0

@singleton
class BlueToothDaemon:
    def __init__(self) -> None:
        self.devices = dict({})
        self.updateCounter = 0
        TickCenter().unschedule(self)
        TickCenter().schedule(self, 3)

    def tick(self, dt):
        for d in self.devices.values():
            if d.exists and not d.paired:
                self._pairDevice(d.mac)
        for d in self.devices.values():
            if d.exists and d.paired and not d.trusted:
                self._trustDevice(d.mac)
        for d in self.devices.values():
            if d.exists and d.paired and d.trusted and not d.connected:
                self._connectDevice(d.mac)
        for d in self.devices.keys():
            self._checkDevice(d)

        #print(datetime.now().strftime("%H:%M:%S"))
    
    def isDeviceConnected(self, macAddr):
        return macAddr in self.devices and self.devices[macAddr].connected
    
    def addDevice(self, macAddr):
        self.devices[macAddr] = BlueToothDevice(macAddr)
        self._checkDevice(macAddr)
        Terminal().runAsync("bluetoothctl scan on", self._onScanLine)
    
    def _onScanLine(self, line):
        print("new device %s" % (line))
    
    def _connectDevice(self, macAddr):
        state = self.devices[macAddr]
        if not state.connected and not state.isconnecting:
            state.isconnecting = True
            Terminal().run("bluetoothctl connect %s" % (macAddr))
            state.isconnecting = False

    def _trustDevice(self, macAddr):
        state = self.devices[macAddr]
        if not state.trusted:
            Terminal().run("bluetoothctl trust %s" % (macAddr))

    def _pairDevice(self, macAddr):
        state = self.devices[macAddr]
        if not state.paired:
            Terminal().run("bluetoothctl pair %s" % (macAddr))
    
    def _checkDevice(self, macAddr):
        state = self.devices[macAddr]
        ret = Terminal().run("bluetoothctl info %s" % (macAddr))
        state.paired = ret.find("Paired: yes") != -1
        state.trusted = ret.find("Trusted: yes") != -1
        self._updateConnected(state, ret.find("Connected: yes") != -1)
    
    def _updateConnected(self, state, connected):
        if state.connected != connected:
            print("BlueToothDaemon::_updateConnected ----> %s connect phase from %s to %s" % (state.mac, str(state.connected), connected))
            state.connected = connected
            if connected:
                state.connectTime = Utils.getTimeStamp()
                EventCenter().trigger(events.EVENT_BLUETOOTH_CONNECT, state.mac)
